package com.bestv.lucene;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * XML 索引器
 * User: Henry
 * Date: 14-5-6
 */
public class XMLIndexer {
    private IndexWriter indexWriter;

    public XMLIndexer(String indexDir) throws IOException {
        Analyzer analyzer = new CJKAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_10_4, analyzer);
        Directory dir = FSDirectory.open(new File(indexDir));
        indexWriter = new IndexWriter(dir, iwc);
    }

    public void close() throws IOException {
        indexWriter.close();
    }

    public int index() throws IOException {
        File xmlFile = new File("/tmp/test.xml");
        SAXReader saxReader = new SAXReader();
        org.dom4j.Document doc = null;
        try{
            doc = saxReader.read(xmlFile);
        }catch(DocumentException e){
            e.printStackTrace();
        }

        assert doc != null;
        Element rootElement = doc.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while(iterator.hasNext()){
            Element element = (Element)iterator.next();
            indexElement(element);
        }
        return indexWriter.numDocs();
    }

    private void indexElement(Element element) throws IOException {
        Document doc = getDocument(element);
        indexWriter.addDocument(doc);
    }

    private Document getDocument(Element element) {
        Document doc = new Document();
        doc.add(new StringField("ProgramId", element.element("Id").getText(), Field.Store.YES));
        doc.add(new TextField("Name", element.element("Name").getText(), Field.Store.YES));
        return doc;
    }
}
